<template>
  <div class="custom-upload">
    <el-upload
      class="upload-wrapper"
      action="#"
      :accept="accept"
      :drag="false"
      multiple
      :file-list="fileList"
      :show-file-list="showFileList"
      :before-upload="before"
      :on-progress="handleProgress"
      :on-success="success"
      :on-remove="remove"
      :on-error="error"
      :http-request="uploadRequest"
      :limit="limit"
      :on-exceed="handleExceed"
      :on-preview="preview"
      :disabled="disabled"
    >
      <el-button
        type="text"
        class="upload-botton"
        v-if="!disabled"
      >
        <div class="upload-botton-content">
          <div class="upload-botton-text">点击上传</div>
          <div class="upload-botton-icon"></div>
        </div>
      </el-button>
    </el-upload>
    <el-progress
      class="upload-progress"
      v-if="
        showProgress && progress !== 0 && progress !== 100
      "
      :percentage="progress"
      color="#409eff"
    ></el-progress>
  </div>
</template>

<script>
import {
  noticeFileUpload,
  noticeFileDownload,
  noticeFileDelete
} from '@/api/wisdomBuild'
import {
  handleDaochu,
  downloadOneFile
} from '@/api/projectRecord'
import request from '@/utils/request'
// 使用说明请前往README.md
export default {
  props: {
    value: { type: Array, default: () => [] }, // 双向绑定的文件数据
    accept: {
      type: String,
      default:
        '.doc,.docx,.pdf,.png,.jpg,.jpeg,.dwg,.mp4,.gif'
    }, // 上传文件接受的格式
    maxSize: { type: Number, default: 0 }, // 文件大小上限
    limit: { type: Number, default: 100 }, // 最大文件上传数量
    disabled: { type: Boolean, default: false },
    showFileList: { type: Boolean, default: true },
    showProgress: { type: Boolean, default: false },
    uploadUrl: {
      type: String,
      default: '/resource/file/upload/file'
    }, // 上传地址
    formData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      defaultFileList: [],
      fileList: [],
      progress: 0
    }
  },
  watch: {
    value: {
      handler() {
        if (this.value.length !== this.fileList.length) {
          this.fileList = this.transformFile(this.value)
          this.defaultFileList = this.fileList
        }
      },
      deep: true,
      immediate: true
    },
    fileList: {
      handler() {
        if (this.isAllSuccess) {
          const files = []
          this.fileList.forEach((item) => {
            files.push({
              fileId: item.response.data,
              attachmentId: item.response.data,
              fileName: item.name,
              filePath: item.url,
              pkid: item.pkid,
              refId: item.refId
            })
          })
          this.$emit('input', this.fileList)
          this.$emit('uploadSuccess', this.fileList)
        }
      },
      deep: true
    }
  },
  computed: {
    isAllSuccess() {
      var allLength = this.fileList.length
      var successLength = 0
      this.fileList.forEach((item) => {
        if (item.status === 'success') {
          successLength += 1
        }
      })
      return successLength === allLength
    }
  },
  mounted() {},
  methods: {
    // 转换文件
    transformFile(files) {
      let tempFlie = []
      files.forEach((file) => {
        tempFlie.push({
          name: file.fileName,
          status: 'success',
          uid: file.pkid,
          pkid: file.pkid,
          url: file.filePath,
          refId: file.refId,
          extra: file,
          response: {
            data: file.attachmentId || file.fileId,
            message: null,
            success: true
          }
        })
      })
      return tempFlie
    },
    before(file) {
      if (this.maxSize) {
        const maxSize =
          file.size / 1024 / 1024 < this.maxSize
        if (!maxSize) {
          this.$message.warning(
            `上传文件大小不能超过 ${this.maxSize}MB!`
          )
          return false
        }
      }

      if (
        !this.accept.includes(file.name.split('.').pop())
      ) {
        this.$message.warning(
          `格式错误，请上传文件名后缀为${this.accept}的文件`
        )
        return false
      }
    },
    change(file, fileList) {
      file.tempImg = URL.createObjectURL(file.raw)
      this.fileList = fileList
    },
    success(res, file, fileList) {
      this.fileList = fileList
    },

    handleProgress() {},
    remove(file, fileList) {
      this.fileList = fileList
    },
    error(err) {
      this.$message.error({
        title: '上传文件错误',
        message: err
      })
    },
    del(index) {
      this.fileList.splice(index, 1)
    },
    uploadRequest(param) {
      const data = new FormData()
      data.append('file', param.file)
      for (let key in this.formData) {
        data.append(key, this.formData[key])
      }
      request({
        method: 'post',
        url: this.uploadUrl,
        data: data,
        onUploadProgress: (progressEvent) => {
          this.progress = parseInt(
            ((progressEvent.loaded / progressEvent.total) *
              100) |
              0,
            10
          )
        }
      })
        .then(async (res) => {
          param.onSuccess(res)
        })
        .catch((err) => {
          param.onError(err)
        })
    },
    handleExceed(file) {
      this.$message.warning(`最多上传${this.limit}个文件！`)
    },
    preview(file) {
      this.downloadFile(file)
    },
    downloadFile(file) {
      downloadOneFile({ fileId: file.response.data }).then(
        (res) => {
          const blob = new Blob([res]) // 把得到的结果用流对象转一下
          const a = document.createElement('a') // 创建一个<a></a>标签
          a.href = URL.createObjectURL(blob) // 将流文件写入a标签的href属性值
          a.download = file.fileName || file.name // 设置文件名
          a.style.display = 'none' // 障眼法藏起来a标签
          document.body.appendChild(a) // 将a标签追加到文档对象中
          a.click() // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
          a.remove() // 一次性的，用完就删除a标签
        }
      )
    }
  }
}
</script>

<style lang="scss">
.custom-upload {
  position: relative;
  .upload-wrapper {
    position: relative;
    .upload-botton {
      &-content {
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }
      &-text {
        color: #00baff;
        margin-right: 5px;
      }
      &-icon {
        width: 16px;
        height: 14px;
        background: url('~@/assets/images/wisdom-construction/upload-file.png');
        background-size: 100% 100%;
      }
    }
  }
  .upload-progress {
    position: absolute;
    left: 0;
    bottom: -55px;
    .el-progress-bar {
      width: 360px;
    }
    .el-progress__text {
      display: none;
    }
  }
}
</style>
